from flask import Flask, render_template, jsonify, request
from datetime import datetime
from scheduler import init_scheduler, JOB_STATUS
from database import Database
import os

app = Flask(__name__)

# 从环境变量获取数据库路径，如果没有则使用默认值
DATABASE_PATH = os.getenv('DATABASE_PATH', 'jobs.db')
db = Database(DATABASE_PATH)

# 初始化数据库
db.init_db()

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/api/job_list")
def job_list():
    jobs = db.get_all_jobs()
    print(jobs)
    # 将元组转换为字典
    job_list = []
    for job in jobs:
        job_dict = {
            'id': job['id'],
            'name': job['name'],
            'source_host': job['source_host'],
            'source_port': job['source_port'],
            'source_username': job['source_username'],
            'source_password': job['source_password'],
            'target_host': job['target_host'],
            'target_port': job['target_port'],
            'target_username': job['target_username'],
            'target_password': job['target_password'],
            'projects': job['projects'],
            'status': job['status'],
            'progress': job['progress'],
            'error_message': job['error_message']
        }
        job_list.append(job_dict)
    return jsonify(job_list)

@app.route("/api/add_job", methods=['POST'])
def add_job():
    try:
        data = request.json
        new_job = db.add_job(data)
        return jsonify(new_job), 201
    except Exception as e:
        print(f"Error adding job: {e}")
        return jsonify({'error': str(e)}), 500

@app.route("/api/delete_job/<int:job_id>", methods=['DELETE'])
def delete_job(job_id):
    """删除指定任务
    Args:
        job_id: 任务ID
    Returns:
        JSON响应，包含删除结果
    """
    try:
        success = db.delete_job(job_id)
        if success:
            return jsonify({'message': f'任务 {job_id} 已删除'}), 200
        else:
            return jsonify({'error': f'任务 {job_id} 不存在'}), 404
    except Exception as e:
        print(f"删除任务时出错: {e}")
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    init_scheduler(DATABASE_PATH)  # 启动调度器，传入数据库路径
    # 获取端口号，默认为8000
    PORT = int(os.getenv('PORT', 8000))
    app.run(debug=True, host='0.0.0.0', port=PORT)  # 使用动态端口号